import { Component, OnInit, ViewChild } from '@angular/core';
import { NewsService, NewsQueryParameter } from '../../service/news.service';
import { News } from '../../domain/news';
import { PagerComponent } from '../../component/pager/pager.component';
import { Toastr } from '../../common/toastr';
import { NavbarService } from '../../component/navbar/navbar.service';
import { ModalService } from '../../component/modal/modal.service';
import { MessageBoxResult } from '../../component/modal/messageBoxResult';

@Component({
    moduleId: module.id,
    templateUrl: 'news.component.html'
})
export class NewsComponent implements OnInit {
    private title: string = "新闻管理";
    private subTitle: string = "管理新闻信息";
    private newsList: News[] = [];
    private queryParams: NewsQueryParameter = {
        currentPage: 1,
        pageSize: 10,
        title: ""
    };

    @ViewChild(PagerComponent)
    private pager: PagerComponent;

    constructor(
        private newsSvr: NewsService,
        private modal: ModalService,
    ) {
        NavbarService.Current.OnAddData = () => {
            console.log("new page add data handle!");
            NavbarService.Current.Navigate(['/main/news/create' ]);
        }
    }

    ngOnInit() {
        this.getNewsList();
        this.pager.OnPageIndexChanged = (pageIndex: number) => {
            this.queryParams.currentPage = pageIndex;
            this.getNewsList();
        }
    }

    async getNewsList() {
        try {
            let r = await this.newsSvr.GetNewsList(this.queryParams);
            this.newsList = r.list;
            this.pager.Load(r.count);
        } catch (error) {
            Toastr.Error(error);
        }
    }

    goNewsInfo(id: number) {
        NavbarService.Current.Navigate(['/main/news/info', id]);
    }

    editNews(id: number) {
        NavbarService.Current.Navigate(['/main/news/edit', id]);
    }

    async delNews(id: number) {
        try {
            let r = await this.modal.Show("提示信息", "是否要删除新闻?");
            if (r == MessageBoxResult.Ok) {
                await this.newsSvr.DeleteNews(id);
                this.getNewsList();
            }
        } catch (error) {
            Toastr.Error(error);
        }

    }
}